<template>
  <div class="course-hours">
    <div class="page-header">
      <h1 class="page-title">教学课时管理</h1>
      <p class="page-subtitle">管理您的教学课时信息</p>
      <div class="user-info" v-if="userStore.user">
        <el-tag type="info" size="small">
          当前用户：{{ userStore.user.name || userStore.user.username }}
        </el-tag>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="20" style="margin-bottom: 24px;">
      <el-col :span="6">
        <el-card>
          <div class="stat-item">
            <div class="stat-value">{{ totalStandardHours }}</div>
            <div class="stat-label">总标准课时量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-item">
            <div class="stat-value">{{ totalConvertedHours }}</div>
            <div class="stat-label">总折合课时量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-item">
            <div class="stat-value">{{ courseCount }}</div>
            <div class="stat-label">课程门数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-item">
            <div class="stat-value">{{ totalStudents }}</div>
            <div class="stat-label">总学生数</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="success" @click="exportData">
        <el-icon><Download /></el-icon>
        导出数据
      </el-button>
      <el-button type="primary" @click="openFormDialog()">
        <el-icon><Plus /></el-icon>
        新增教学课时
      </el-button>
      <el-select v-model="selectedAcademicYear" placeholder="选择学年学期" style="width: 250px; margin-left: 12px;" @change="handleAcademicYearChange">
        <el-option
          label="全部学期"
          value=""
        />
        <el-option
          v-for="semester in semesterConfigs"
          :key="semester.academicYear"
          :label="semester.academicYear"
          :value="semester.academicYear"
        />
      </el-select>
      <el-button style="margin-left: 12px;" @click="refreshData">刷新数据</el-button>
    </div>

    <!-- 课程列表 -->
    <el-card style="margin-top: 20px;">
      <template #header>
        <span>教学课时列表</span>
      </template>
      <el-table :data="filteredCourseHours" style="width: 100%" v-loading="loading">
        <el-table-column prop="academicYear" label="学年学期" width="200" />
        <el-table-column prop="courseName" label="课程名称" min-width="180" />
        <el-table-column prop="courseNature" label="课程性质" width="120" />
        <el-table-column prop="theoryHours" label="理论学时" width="100" />
        <el-table-column prop="standardClassCount" label="折合标准教学班" width="150" />
        <el-table-column prop="standardHours" label="标准课时量" width="120" />
        <el-table-column prop="conversionFactor" label="折算系数" width="100" />
        <el-table-column prop="convertedHours" label="折合课时量" width="120" />
        <el-table-column prop="teachingClass" label="授课班级" min-width="150" />
        <el-table-column prop="studentCount" label="修读人数" width="100" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="openFormDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑教学课时' : '新增教学课时'"
      width="1200px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学年学期" prop="academicYear">
              <el-select v-model="formData.academicYear" placeholder="请选择学年学期" style="width: 100%">
                <el-option
                  v-for="semester in semesterConfigs"
                  :key="semester.academicYear"
                  :label="semester.academicYear"
                  :value="semester.academicYear"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="formData.courseName" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程性质" prop="courseNature">
              <el-input v-model="formData.courseNature" placeholder="请输入课程性质" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="理论学时" prop="theoryHours">
              <el-input-number v-model="formData.theoryHours" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="授课班级" prop="teachingClass">
              <el-input v-model="formData.teachingClass" placeholder="请输入授课班级（可选）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修读人数" prop="studentCount">
              <el-input-number v-model="formData.studentCount" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="折合标准教学班" prop="standardClassCount">
              <el-input-number v-model="formData.standardClassCount" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折算系数" prop="conversionFactor">
              <el-input-number v-model="formData.conversionFactor" :min="0" :precision="4" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标准课时量" prop="standardHours">
              <el-input v-model="calculatedStandardHours" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折合课时量" prop="convertedHours">
              <el-input v-model="calculatedConvertedHours" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 授课教师及分配课时量 -->
        <el-form-item label="授课教师及分配课时量" prop="members">
          <div class="members-section">
            <div class="members-header">
              <span>授课教师列表</span>
              <el-button type="primary" size="small" @click="addMember">
                <el-icon><Plus /></el-icon>
                添加教师
              </el-button>
            </div>
                         <el-table :data="formData.members" style="width: 100%">
               <el-table-column label="教师姓名" width="150">
                 <template #default="scope">
                   <el-input v-model="scope.row.userName" placeholder="请输入教师姓名" style="width: 100%" />
                 </template>
               </el-table-column>
              <el-table-column label="分配课时量" width="150">
                <template #default="scope">
                  <el-input-number v-model="scope.row.allocatedHours" :min="0" :precision="2" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column label="角色" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.role" placeholder="如：主讲教师、助教" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button size="small" type="danger" @click="removeMember(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
 import {
   createCourseHours,
   updateCourseHours,
   deleteCourseHours,
   getMyCourseHours,
   getSemesterConfig
 } from '@/api/courseHours'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const formDialogVisible = ref(false)
const isEdit = ref(false)
const selectedAcademicYear = ref('')
const courseHours = ref([])
const semesterConfigs = ref([])


// 表单数据
const formData = ref({
  id: null,
  academicYear: '',
  courseName: '',
  courseNature: '',
  theoryHours: 0,
  teachingClass: '',
  studentCount: 0,
  standardClassCount: 1,
  conversionFactor: 1.0,
  members: []
})

// 表单验证规则
const formRules = {
  academicYear: [{ required: true, message: '请选择学年学期', trigger: 'change' }],
  courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  theoryHours: [{ required: true, message: '请输入理论学时', trigger: 'blur' }],
  standardClassCount: [{ required: true, message: '请输入折合标准教学班', trigger: 'blur' }],
  conversionFactor: [{ required: true, message: '请输入折算系数', trigger: 'blur' }],
  members: [{ 
    validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('至少需要添加一个授课教师'));
      } else {
        for (let i = 0; i < value.length; i++) {
          if (!value[i].userName || value[i].userName.trim() === '') {
            callback(new Error(`第${i + 1}个教师的姓名不能为空`));
            return;
          }
        }
        callback();
      }
    }, 
    trigger: 'change' 
  }]
}

const formRef = ref()

// 计算属性
const filteredCourseHours = computed(() => {
  if (!selectedAcademicYear.value) {
    return courseHours.value
  }
  return courseHours.value.filter(item => item.academicYear === selectedAcademicYear.value)
})

const totalStandardHours = computed(() => {
  const currentUserName = userStore.user?.name || userStore.user?.username || ''
  const result = filteredCourseHours.value.reduce((total, item) => {
    let itemTotal = 0
    
    // 只统计当前用户作为成员的课时量
    item.members.forEach(member => {
      if (member.userName === currentUserName) {
        itemTotal += (member.allocatedHours || 0)
        console.log(`课程: ${item.courseName}, 用户: ${currentUserName}, 分配课时: ${member.allocatedHours}`)
      }
    })
    
    return total + itemTotal
  }, 0)
  
  console.log(`用户 ${currentUserName} 的总标准课时量: ${result}`)
  return result.toFixed(2)
})

const totalConvertedHours = computed(() => {
  return filteredCourseHours.value.reduce((total, item) => {
    let itemTotal = 0
    const currentUserName = userStore.user?.name || userStore.user?.username || ''
    
    // 只统计当前用户作为成员的课时量
    item.members.forEach(member => {
      if (member.userName === currentUserName) {
        // 按用户实际分配的课时量计算折合课时量
        const memberRatio = (member.allocatedHours || 0) / (item.standardHours || 1)
        itemTotal += (item.convertedHours || 0) * memberRatio
      }
    })
    
    return total + itemTotal
  }, 0).toFixed(2)
})

const courseCount = computed(() => {
  const currentUserName = userStore.user?.name || userStore.user?.username || ''
  
  // 只统计当前用户参与的课程数量
  return filteredCourseHours.value.filter(item => {
    return item.members.some(member => member.userName === currentUserName)
  }).length
})

const totalStudents = computed(() => {
  const currentUserName = userStore.user?.name || userStore.user?.username || ''
  
  // 只统计当前用户参与课程的学生数
  return filteredCourseHours.value.reduce((sum, item) => {
    // 检查当前用户是否参与这门课程
    const isUserInvolved = item.members.some(member => member.userName === currentUserName)
    return sum + (isUserInvolved ? (item.studentCount || 0) : 0)
  }, 0)
})

const calculatedStandardHours = computed(() => {
  if (formData.value.theoryHours && formData.value.standardClassCount) {
    return (formData.value.theoryHours * formData.value.standardClassCount).toFixed(2)
  }
  return '0.00'
})

const calculatedConvertedHours = computed(() => {
  if (formData.value.theoryHours && formData.value.standardClassCount && formData.value.conversionFactor) {
    return (formData.value.theoryHours * formData.value.standardClassCount * formData.value.conversionFactor).toFixed(2)
  }
  return '0.00'
})

// 方法
 const loadData = async () => {
   loading.value = true
   try {
     const [courseHoursData, semesterData] = await Promise.all([
       getMyCourseHours(),
       getSemesterConfig()
     ])
     
     courseHours.value = courseHoursData || []
     semesterConfigs.value = semesterData || []
     
     // 不设置默认学年学期，让用户可以选择"全部学期"
   } catch (error) {
     console.error('加载数据失败:', error)
     ElMessage.error('加载数据失败')
   } finally {
     loading.value = false
   }
 }

const refreshData = () => {
  loadData()
}

const handleAcademicYearChange = () => {
  // 学年学期变化时，数据会自动通过计算属性过滤
}

const openFormDialog = (row = null) => {
  if (row) {
    // 编辑模式
    isEdit.value = true
    formData.value = {
      id: row.id,
      academicYear: row.academicYear,
      courseName: row.courseName,
      courseNature: row.courseNature,
      theoryHours: row.theoryHours,
      teachingClass: row.teachingClass || '',
      studentCount: row.studentCount || 0,
      standardClassCount: row.standardClassCount,
      conversionFactor: row.conversionFactor,
             members: row.members ? row.members.map(member => ({
         userName: member.userName || '',
         allocatedHours: member.allocatedHours || 0,
         role: member.role || '授课教师'
       })) : []
    }
  } else {
    // 新增模式
    isEdit.value = false
    formData.value = {
      id: null,
      academicYear: selectedAcademicYear.value || (semesterConfigs.value[0]?.academicYear || ''),
      courseName: '',
      courseNature: '',
      theoryHours: 0,
      teachingClass: '',
      studentCount: 0,
      standardClassCount: 1,
      conversionFactor: 1.0,
      members: []
    }
  }
  formDialogVisible.value = true
}

const addMember = () => {
  formData.value.members.push({
    userName: '',
    allocatedHours: 0,
    role: '授课教师'
  })
}

const removeMember = (index) => {
  formData.value.members.splice(index, 1)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
         // 验证成员信息
     if (formData.value.members.length === 0) {
       ElMessage.error('至少需要添加一个授课教师')
       return
     }
     
     for (let i = 0; i < formData.value.members.length; i++) {
       const member = formData.value.members[i]
       if (!member.userName || member.userName.trim() === '') {
         ElMessage.error(`第${i + 1}个教师的姓名不能为空`)
         return
       }
     }
    
    submitting.value = true
    
    if (isEdit.value) {
      await updateCourseHours(formData.value.id, formData.value)
      ElMessage.success('更新成功')
    } else {
      await createCourseHours(formData.value)
      ElMessage.success('创建成功')
    }
    
    formDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败: ' + (error.message || error))
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个教学课时吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCourseHours(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.message || error))
    }
  }
}

// 导出数据
const exportData = async () => {
  const { exportData: exportUtil } = await import('@/utils/exportUtils')
  
  const filters = {
    semester: selectedAcademicYear.value
  }
  
  await exportUtil('course-hours', filters, '教学课时列表.xlsx')
}

// 监听数据变化，自动计算课时量
watch(() => [formData.value.theoryHours, formData.value.standardClassCount, formData.value.conversionFactor], () => {
  // 数据变化时，计算属性会自动更新
}, { deep: true })

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.course-hours {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.user-info {
  margin-top: 8px;
}

.stat-item {
  text-align: center;
  padding: 16px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.members-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
}

.members-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
